import axios from 'axios';
import store from '@/store';
// import router from '@/router';

const request = axios.create({
  // timeout: 2000
  // baseURL:
  // headers:
});

// function redirectLogin() {
//   router.push({
//     name: 'User',
//   });
// }

// 获取接口baseURL
function getBaseURL(url) {
  let baseURL = '';
  if (url.startsWith('/boss')) {
    baseURL = 'http://eduboss.lagounews.com';
  } else {
    baseURL = 'http://edufront.lagounews.com';
  }
  return baseURL;
}

// 请求拦截器
request.interceptors.request.use((config) => {
  // 判断 config.url 的前缀，来进行请求 baseURL 的设置
  const nconfig = config;
  nconfig.baseURL = getBaseURL(config.url);
  if (store.state.user) {
    nconfig.headers = { Authorization: store.state.user.access_token };
  }
  return nconfig;
});

// 添加响应拦截器
request.interceptors.response.use(
  (response) => response,
  async (error) => {
  // 对响应错误做点什么
    if (error.response) {
      const { status } = error.response;
      if (status === 401) {
        if (!store.state.user) {
          return Promise.reject(error);
        }
        console.log('用户登录信息失效');

        const { data } = await request({
          method: 'POST',
          url: '/front/user/refresh_token',
          params: { refreshtoken: store.state.user.refresh_token },
        });
        if (data.state !== 1) {
          console.log('token update failed');
          store.commit('setUser', null);
          return Promise.reject(error);
        }
        store.commit('setUser', data.content);
        console.log('token updated!');
        return request(error.config);
      }
      if (status === 403) {
        console.log('没有权限，请联系管理员');
      } else if (status === 404) {
        console.log('请求资源不存在');
      } else if (status >= 500) {
        console.log('服务端错误，请联系管理员');
      } else {
        console.log('未知错误，请联系管理员');
      }
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    return Promise.reject(error);
  },
);

export default request;
